// FilePathAutoRename.cpp

#include "StdAfx.h"


#include <algorithm>

#include "FileFind.h"

#include "FilePathAutoRename.h"


namespace Common
{
namespace FileSystem
{
static bool MakeAutoName(const CString &name,
    const CString &extension, unsigned value, CString &path)
{
  TCHAR number[16];
  _ultot(value, number, 10);
  path = name;
  path += number;
  path += extension;
  return FileSystem::Find::DoesFileOrDirExist(path);
}

bool AutoRenamePath(CString &fullProcessedPath)
{
  CString path;
  int dotPos = fullProcessedPath.ReverseFind(_T('.'));

  int slashPos = fullProcessedPath.ReverseFind(_T('/'));
  #ifdef _WIN32
  int slash1Pos = fullProcessedPath.ReverseFind(_T('\\'));
  slashPos = max(slashPos, slash1Pos);
  #endif

  CString name, extension;
  if (dotPos > slashPos && dotPos > 0)
  {
    name = fullProcessedPath.Left(dotPos);
    extension = fullProcessedPath.Mid(dotPos);
  }
  else
    name = fullProcessedPath;
  name += _T('_');
  unsigned left = 1, right = (1 << 30);
  while (left != right)
  {
    unsigned mid = (left + right) / 2;
    if (MakeAutoName(name, extension, mid, path))
      left = mid + 1;
    else
      right = mid;
  }
  return !MakeAutoName(name, extension, right, fullProcessedPath);
}

}
}